package com.cherrish.demo;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.OperatingSystemMXBean;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author cherrish
 * @time 2019-02-20 10:51
 * @name SystemInfoUtil
 * @desc:
 */
public class SystemInfoUtil {
    private static final String FORMAT_PATTERN = "#.00";

    private static final String UNIT_B = "Byte";
    private static final String UNIT_KB = "KB";
    private static final String UNIT_MB = "MB";
    private static final String UNIT_GB = "GB";

    private static final long KB = 1024L;
    private static final long MB = 1048576L;
    private static final long GB = 1073741824L;

    public static Map<String, String> getSystemDir(){
        FileSystemView fsv = FileSystemView.getFileSystemView();
        File[] fs = File.listRoots();
        Map<String, String> map = new LinkedHashMap<>(fs.length);
        for (int i = 0; i < fs.length; i++) {
            String dirName = fsv.getSystemDisplayName(fs[i]);
            long totalSpace = fs[i].getTotalSpace();
            long usableSpace = fs[i].getUsableSpace();
            long freeSpace = fs[i].getFreeSpace();

            map.put(dirName, totalSpace + ","+ freeSpace);
        }
        return map;
    }

    public static long[] getMemery(){
        OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();

        String name = osmxb.getName();
        String version = osmxb.getVersion();

        String arch = osmxb.getArch();

        long a = osmxb.getAvailableProcessors();
        double d = osmxb.getSystemLoadAverage();

        MemoryMXBean mmxb = ManagementFactory.getMemoryMXBean();

        System.out.println(name);
        System.out.println(version);
        System.out.println(arch);
        System.out.println(a);
        System.out.println(d);

        System.out.println(mmxb.getHeapMemoryUsage());
        System.out.println(mmxb.getNonHeapMemoryUsage());
        return null;
    }

    public static String formetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat(FORMAT_PATTERN);
        String fileSizeString = "";
        if (fileS < KB) {
            fileSizeString = df.format((double) fileS) + UNIT_B;
        } else if (fileS < MB) {
            fileSizeString = df.format((double) fileS / KB) + UNIT_KB;
        } else if (fileS < GB) {
            fileSizeString = df.format((double) fileS / MB) + UNIT_MB;
        } else {
            fileSizeString = df.format((double) fileS / GB) + UNIT_GB;
        }
        return fileSizeString;
    }
}
